package auto;


/**
 *
 * @author Jonas
 */
public class GPSDummy implements GPS{
    private static int IDCounter=0;
    private String ID;
    private BoordComputer attachedComp;
    private Mover mover;
    private boolean moving;

    public GPSDummy() {
        ID = "GPS-id"+IDCounter;
        IDCounter++;
        attachedComp = null;
        mover = null;
        moving = false;
    }

    public void subscribe(BoordComputer computer) {
        attachedComp = computer;
        System.out.println("Computer "+computer+" subscribed at "+this);
    }

    public void unsubscribe() {
        if(attachedComp != null)
            System.out.println("Computer "+attachedComp+" unsubscribed");
        attachedComp = null;
        System.out.println("No computer subscribed");
    }

    public void startMoving() {
        if(!moving){
            mover = new Mover(attachedComp);
            System.out.println("Buckle up");
            new Thread(mover).start();
        }
        moving = true;
    }

    public void stopMoving() {
        if(mover != null)
            mover.stopDriving();
        moving = false;
    }

    @Override
    public String toString() {
        return ID;
    }
    
    public boolean isMoving(){
        return moving;
    }
}

class Mover implements Runnable{
    BoordComputer attachedComp;
    boolean driving;
    int counter;

    public Mover(BoordComputer attachedComp) {
        this.attachedComp = attachedComp;
    }

    public void run() {
        driving = true;
        while(driving){
            attachedComp.pushData(new Location(counter,counter), System.currentTimeMillis());
            counter++;
            try {
                Thread.sleep(1000 + (int) (Math.random()*2000));
            } catch (InterruptedException ex) {}
        }
        attachedComp.pushData(new Location(counter,counter), System.currentTimeMillis());
    }

    public void stopDriving() {
        this.driving = false;
    }
}